<template>
  <div class="container">
    <div ref="barchart_ref" class="chart"></div>
    <!-- 分页控制器 -->
    <div class="pagination-controls" v-if="totalPage > 1">
      <button
        class="pagination-btn el-icon-caret-left"
        @click="prevPage"
      ></button>
      <span class="page-info"> {{ currPage }} / {{ totalPage }} </span>
      <button
        class="pagination-btn el-icon-caret-right"
        @click="nextPage"
      ></button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      chart: null,
      ndata: [],
      currPage: 1, //当前页
      totalPage: 0, //总页数
      itemsPerPage: 6, //每页显示的项目数
      intervalID: null,
    };
  },
  mounted() {
    this.initChart();
    this.getData();

    //当窗体的尺寸发生改变时，图表大小也随之改变
    window.addEventListener("resize", this.screenAdapter);
  },
  beforeDestroy() {
    this.$bus.$off("chartdata");
    //清除定时器
    // clearInterval(this.intervalID)
    //组件销毁时移除事件
    window.removeEventListener("resize", this.screenAdapter);
  },
  methods: {
    getData() {
      return new Promise((resolve) => {
        this.$bus.$on("chartdata", (res) => {
          this.ndata = res;
          // 更新图表（例如：只显示当前选中的年份）
          resolve(res);
          //每6个元素显示一页
          // 计算总页数
          this.totalPage = Math.ceil(this.ndata.length / this.itemsPerPage);
          this.updateChart();
          // this.startInterval()
        });
      });
    },
    initChart() {
      this.chart = this.$echarts.init(this.$refs.barchart_ref);
      const option = {
        title: {
          text: "各地区年际npp",
          left: "center",
          top: "2%",
          textStyle: {
            color: "#fff",
            fontSize: 16,
            fontFamily:"华文楷体",
            fontWeight: 400,
          },
        },
        //高亮显示
        tooltip: {
          //触发条件，鼠标移入坐标轴
          trigger: "axis",
          //高亮类型
          axisPointer: {
            //线条
            type: "line",
            z: 0,
            lineStyle: {
              type: "solid",
              color: "#2D3443",
            },
          },
          backgroundColor: "rgba(16,12,42,0.9)",
          textStyle: {
            color: "#fff",
          },
        },
        //坐标轴位置
        grid: {
          bottom: this.totalPage > 1 ? "12%" : "5%", // 为分页控件留出空间
          left: "5%",
          right: "5%",
          // top: "19%",
          containLabel: true, //包不包括文字
        },
        xAxis: {
          type: "category",
          axisTick: {
            //x轴刻度与柱子对齐
            alignWithLabel: true,
          },
        },
        yAxis: {
          type: "value",
          name: "NPP均值",
          nameTextStyle: {
            color: "#fff",
          },
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
          },
          axisLine: {
            lineStyle: {
              color: "#fff",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(255,255,255,0.2)",
            },
          },
        },

        series: [
          {
            type: "bar",
            itemStyle: {
              //柱状图圆角
              borderRadius: [10, 10, 0, 0],
              //设置颜色渐变
              color: new this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: "rgba(255, 112, 112, 0.8)" }, //0%位置
                { offset: 1, color: "rgba(145, 204, 117, 1)" }, //100%位置
              ]),
            },
            emphasis: {
              itemStyle: {
                color: new this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: "rgba(255, 150, 150, 1)" },
                  { offset: 1, color: "rgba(165, 224, 137, 1)" },
                ]),
              },
            },
            label: {
              //数值标签
              show: true,
              position: "top",
              fontSize: 12,
              formatter: "{c}",
            },
          },
        ],
      };
      this.chart.setOption(option);
    },
    updateChart() {
      const name = this.ndata.map((item) => item.NAME);
      const nppdata = this.ndata.map((item) => {
        let res = 0;
        if (item.npp_mean) {
          res =
            typeof item.npp_mean === "number" ? item.npp_mean.toFixed(2) : 0.0;
        } else {
          res =
            500 +
            (Math.floor(Math.random() * 9) + 1) * 10 +
            (Math.floor(Math.random() * 9) + 1) +
            (Math.floor(Math.random() * 9) + 1) / 10;
        }
        return res;
      });
      //起始索引
      const start = (this.currPage - 1) * 6;
      //结束索引
      const end = this.currPage * 6;
      //截取
      const showName = name.slice(start, end);
      const showValue = nppdata.slice(start, end);
      this.chart.setOption({
        xAxis: {
          type: "category",
          data: showName,
        },
        series: [
          {
            data: showValue,
          },
        ],
      });
    },
    //开启定时器
    startInterval() {
      //如果有定时器开启，就先清除
      if (this.intervalID) {
        clearInterval(this.intervalID);
      }
      this.intervalID = setInterval(() => {
        this.currPage++;
        //到最后一页之后，重新第一页
        if (this.currPage >= this.totalPage) {
          this.currPage = 1;
        }
        //得更新一下图表
        this.updateChart();
      }, 3000);
    },
    // 上一页
    prevPage() {
      if (this.currPage > 1) {
        this.currPage--;
        this.updateChart();
      } else {
        this.currPage = this.totalPage;
        this.updateChart();
      }
    },
    // 下一页
    nextPage() {
      if (this.currPage < this.totalPage) {
        this.currPage++;
        this.updateChart();
      } else {
        this.currPage = 1;
        this.updateChart();
      }
    },
    // 窗口调整适配
    screenAdapter() {
      if (this.chart) {
        this.chart.resize();
      }
    },
  },
  watch: {
    // 监听数据变化，重置到第一页
    // ndata() {
    //   this.currPage = 1;
    // }
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
}
.chart {
  width: 100%;
  flex: 0.90;
}
.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
  padding: 5px;
}

.pagination-btn {
  padding: 2px 5px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
}

.pagination-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pagination-controls {
    flex-direction: column;
    gap: 10px;
    padding: 10px;
  }

  .pagination-btn {
    padding: 6px 15px;
    font-size: 12px;
  }

  .page-info {
    font-size: 12px;
  }
}
</style>